import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/utils/base_component_utils.dart';

///**
///* @fileName: select_period_dialog
///* @author: hrongyong
///* @date-time: 12/10/21 10:41 AM
///* @email: hrongyong@gmail.com
///* description:
///* <fileName> <author> <date-time> <email> <description>
///* 文件名 作者姓名 创建时间 作者邮箱 文件描述
///*/
class SelectPeriodDialog extends StatefulWidget {
  // 显示列表 外面传进来不用再新建
  final List<String> periodList;

  // 默认选中
  final int selectPeriodIndex;

  // 自定义的位置
  final int customizeIndex;

  // 自定义开始
  final DateTime customizeStart;

  // 自定义结束
  final DateTime customizeEnd;

  // 预留高度
  final double reservedHeight;

  final Function(int selectPeriodIndex, DateTime start, DateTime end) selectCallBack;

  const SelectPeriodDialog({Key key, @required this.reservedHeight, @required this.selectPeriodIndex, @required this.customizeStart, @required this.customizeEnd, @required this.selectCallBack, @required this.periodList, @required this.customizeIndex}) : super(key: key);

  @override
  _SelectPeriodDialogState createState() => _SelectPeriodDialogState();
}

class _SelectPeriodDialogState extends State<SelectPeriodDialog> {
  ///标题栏（appbar）
  static double _appbarHeight = AppBar().preferredSize.height;

  /// 自定义时间段
  DateTime _customizeStart;
  DateTime _customizeEnd;
  DateTime _nowDateTime = DateTime.now();

  /// 系统颜色 黑 Color(0xff333333) 白：Color(0xffffffff) 黑白主题选中颜色为Color(0xFFFF004F)
  Color get systemColor => Theme.of(context).primaryColor == Colors.white || Theme.of(context).primaryColor == Color(0xFF333333) ? Color(0xFFFF004F) : Theme.of(context).primaryColor;

  @override
  void initState() {
    super.initState();
    if (widget.customizeStart != null && widget.selectPeriodIndex == widget.customizeIndex) _customizeStart = widget.customizeStart;
    if (widget.customizeEnd != null && widget.selectPeriodIndex == widget.customizeIndex) _customizeEnd = widget.customizeEnd;
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: SafeArea(
        child: Column(
          children: [
            SizedBox(height: _appbarHeight + widget.reservedHeight),
            BaseComponentUtils.buildHorizontalDivider(),
            Container(color: Colors.white, constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.7), child: _buildListView()),
            Expanded(child: InkWell(onTap: () => BaseRouterUtil.getInstance().pop(), child: Container(color: Color(0XAA000000)))),
          ],
        ),
      ),
    );
  }

  Widget _buildListView() {
    return ListView.separated(
      shrinkWrap: true,
      itemCount: widget.periodList.length,
      itemBuilder: (BuildContext context, int index) => _buildItemSwitch(context, index, widget.periodList[index]),
      separatorBuilder: (BuildContext context, int index) => BaseComponentUtils.buildHorizontalDivider(),
    );
  }

  Widget _buildItemSwitch(BuildContext context, int index, String period) {
    switch (period) {
      case '自定义':
        return _buildCustomPeriodItem(context, index);
        break;
      default:
        return _buildItem(context, index);
        break;
    }
  }

  Widget _buildItem(BuildContext context, int index) {
    return InkWell(
      onTap: () => _onItemEvent(index),
      child: Container(
        height: 48,
        padding: EdgeInsets.symmetric(horizontal: 16),
        alignment: Alignment.centerLeft,
        color: widget.selectPeriodIndex == index ? Color(0xFFF8F8F8) : Colors.white,
        child: Text(_getBuildItemText(index), style: TextStyle(color: widget.selectPeriodIndex == index ? this.systemColor : Color(0xFF333333))),
      ),
    );
  }

  Widget _buildCustomPeriodItem(BuildContext context, int index) {
    String _start = _customizeStart != null ? '${_customizeStart.year}-${BaseTransformUtil.format(_customizeStart.month)}-${BaseTransformUtil.format(_customizeStart.day)}' : '';
    String _end = _customizeEnd != null ? '${_customizeEnd.year}-${BaseTransformUtil.format(_customizeEnd.month)}-${BaseTransformUtil.format(_customizeEnd.day)}' : '';
    return Container(
      height: 48,
      color: widget.selectPeriodIndex == index ? Color(0xFFF8F8F8) : Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          Text(widget.periodList[index], style: TextStyle(color: widget.selectPeriodIndex == index ? this.systemColor : Color(0xFF333333))),
          SizedBox(width: 12),
          Expanded(child: _buildCustomizeDateItem(defaultName: '开始时间', onTap: () => _startTimeEvent(index), dateTime: _start)),
          SizedBox(width: 12),
          Text("至"),
          SizedBox(width: 12),
          Expanded(child: _buildCustomizeDateItem(defaultName: '结束时间', onTap: () => _endTimeEvent(index), dateTime: _end)),
        ],
      ),
    );
  }

  Widget _buildCustomizeDateItem({@required String defaultName, @required String dateTime, @required Function() onTap}) {
    return InkWell(
      onTap: onTap,
      child: Container(
        width: double.infinity,
        height: 32,
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.symmetric(horizontal: 4),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: dateTime.isEmpty ? Color(0xFF868686) : this.systemColor, width: 1),
          borderRadius: BorderRadius.circular(4),
        ),
        child: Text(dateTime.isEmpty ? defaultName : dateTime, style: TextStyle(color: dateTime.isEmpty ? Color(0xFF868686) : this.systemColor)),
      ),
    );
  }

  String _getBuildItemText(int index) {
    List<DateTime> _period = getPeriod(widget.periodList[index]);
    String _start = '${_period[0].year}-${BaseTransformUtil.format(_period[0].month)}-${BaseTransformUtil.format(_period[0].day)}';
    String _end = '${_period[1].year}-${BaseTransformUtil.format(_period[1].month)}-${BaseTransformUtil.format(_period[1].day)}';
    String text = widget.periodList[index];
    return "$text ($_start ~ $_end)";
  }

  ///开始时间事件
  void _startTimeEvent(int index) {
    BaseComponentUtils.openDatePicker(context, currentDate: _customizeStart != null ? _customizeStart : null, onDateChanged: (DateTime changed) {
      _customizeStart = changed;

      ///当设置开始日期大于结束日期时，自动将结束日期等于开始日期
      if (_customizeEnd != null && _customizeStart.isAfter(_customizeEnd)) {
        _customizeEnd = _customizeStart;
      }
      if (_customizeStart != null && _customizeEnd != null) {
        ///由于选择后就关闭，所以不再需要刷新
        _onItemEvent(index);
      } else {
        setState(() {});
      }
    });
  }

  ///结束时间事件
  void _endTimeEvent(int index) {
    BaseComponentUtils.openDatePicker(context, currentDate: _customizeEnd != null ? _customizeEnd : null, onDateChanged: (DateTime changed) {
      _customizeEnd = changed;

      ///当设置结束日期小于开始日期时，自动将结束日期等于开始日期
      if (_customizeStart != null && _customizeEnd.isBefore(_customizeStart)) {
        _customizeEnd = _customizeStart;
      }
      if (_customizeStart != null && _customizeEnd != null) {
        ///由于选择后就关闭，所以不再需要刷新
        _onItemEvent(index);
      } else {
        setState(() {});
      }
    });
  }

  void _onItemEvent(int index) {
    widget.selectCallBack(index, getPeriod(widget.periodList[index])[0], getPeriod(widget.periodList[index])[1]);
    BaseRouterUtil.getInstance().pop();
  }

  List<DateTime> getPeriod(String text) {
    DateTime _start;
    DateTime _end;
    switch (text) {
      case '近7天':
        DateTime daysAgo = _nowDateTime.subtract(Duration(days: 6));
        _start = DateTime(daysAgo.year, daysAgo.month, daysAgo.day);
        _end = DateTime(_nowDateTime.year, _nowDateTime.month, _nowDateTime.day, 23, 59, 59, 999);
        break;
      case '昨天':
        DateTime yesterday = _nowDateTime.subtract(Duration(days: 1));
        _start = DateTime(yesterday.year, yesterday.month, yesterday.day);
        _end = DateTime(yesterday.year, yesterday.month, yesterday.day, 23, 59, 59, 999);
        break;
      case '今天':
        _start = DateTime(_nowDateTime.year, _nowDateTime.month, _nowDateTime.day);
        _end = DateTime(_nowDateTime.year, _nowDateTime.month, _nowDateTime.day, 23, 59, 59, 999);
        break;
      case '本周':
        int _weekday = _nowDateTime.weekday;
        DateTime _monday = _weekday == 1 ? _nowDateTime : _nowDateTime.subtract(Duration(days: _weekday - 1));
        DateTime _sunday = _weekday == 7 ? _nowDateTime : _nowDateTime.add(Duration(days: 7 - _weekday));
        _start = DateTime(_monday.year, _monday.month, _monday.day);
        _end = DateTime(_sunday.year, _sunday.month, _sunday.day, 23, 59, 59, 999);
        break;
      case '本月':
        if (_nowDateTime.month == 12) {
          _start = DateTime(_nowDateTime.year, _nowDateTime.month, 1);
          _end = DateTime(_nowDateTime.year, 12, 31, 23, 59, 59, 999);
        } else {
          // 下个月1号
          DateTime nextMonth1st = DateTime(_nowDateTime.year, _nowDateTime.month + 1, 1);
          // 本月最后一天
          DateTime lastDay = nextMonth1st.subtract(Duration(days: 1));
          _start = DateTime(_nowDateTime.year, _nowDateTime.month, 1);
          _end = DateTime(_nowDateTime.year, lastDay.month, lastDay.day, 23, 59, 59, 999);
        }
        break;
      case '本年':
        _start = DateTime(_nowDateTime.year, 1, 1);
        _end = DateTime(_nowDateTime.year, 12, 31, 23, 59, 59, 999);
        break;
      case '自定义':
        _start = DateTime(_customizeStart.year, _customizeStart.month, _customizeStart.day);
        _end = DateTime(_customizeEnd.year, _customizeEnd.month, _customizeEnd.day, 23, 59, 59, 999);
        break;
    }
    return [_start, _end];
  }
}
